//
function add(func, mevent, mkey, mlife) {
	if (!mkey) mkey = '__';
	if (!mlife) mlife = 1;

	let app = getApp();
	let gdata = app.globalData;

	if (!gdata.m_funcs) gdata.m_funcs = {};
	if (!gdata.m_funcs[mevent]) gdata.m_funcs[mevent] = {};

	gdata.m_funcs[mevent][mkey] = {
		func,
		mlife,
	};
}

function doo(mevent, props) {
	if (typeof props == 'undefined') props = null;

	let app = getApp();
	let gdata = app.globalData;

	if (!gdata.m_funcs) gdata.m_funcs = {};
	for (let k in gdata.m_funcs[mevent]) {
		let afunc = gdata.m_funcs[mevent][k];
		if (afunc.mlife == 0) {
			delete gdata.m_funcs[mevent][k];
			continue;
		}

		//执行
		afunc.func(props);

		//不限制
		if (afunc.mlife == -1) continue;

		afunc.mlife--;
		if (afunc.mlife == 0) delete gdata.m_funcs[mevent][k];
	}
}

function del(mevent, mkey) {
	let app = getApp();
	let gdata = app.globalData;

	if (!gdata.m_funcs) return;
	if (!gdata.m_funcs[mevent]) return;

	for (let k in gdata.m_funcs[mevent]) {
		if (!mkey || k == mkey) delete gdata.m_funcs[mevent][k];
	}

	if (Object.keys(gdata.m_funcs[mevent]).length < 1) delete gdata.m_funcs[mevent];
}

module.exports = {
	add,
	doo,
	del,
}
